#include "unpifi.h"

/*
 * 使用编写的库中的提供的取系统接口信息函数
 * 该函数返回一个接口列表
 */

int
main(int argc, char *argv[]) {
	struct ifi_info	*ifi, *ifihead;
	struct sockaddr *sa;
	u_char *ptr;
	int	   i, family = AF_INET, doaliases;

	if (argc != 3) {
		err_quit("usage: %s <inet4|inet6> <doaliases>", argv[0]);
	} else if (strcmp(argv[1], "inet4") == 0) {
		family = AF_INET;
	} else if (strcmp(argv[1], "inet6") == 0) {
		family = AF_INET6;
	} else {
		err_quit("Invalid <Address family>");
	}
	doaliases = atoi(argv[2]);

	for (ifihead = ifi = get_ifi_info(family, doaliases);
			ifi != NULL; ifi = ifi->ifi_next) {
		printf("%s: ", ifi->ifi_name);
		if (ifi->ifi_index != 0) 
			printf("(%d) ", ifi->ifi_index);
		printf("<");
		if (ifi->ifi_flags & IFF_UP)			printf("UP ");
		if (ifi->ifi_flags & IFF_BROADCAST)		printf("BCAST ");
		if (ifi->ifi_flags & IFF_MULTICAST)		printf("MCAST ");
		if (ifi->ifi_flags & IFF_LOOPBACK)		printf("LOOP ");
		if (ifi->ifi_flags & IFF_POINTOPOINT)	printf("P2P ");
		printf(">\n");

		//MAC
		if ((i = ifi->ifi_hlen) > 0) {
			ptr = ifi->ifi_haddr;
			printf("\t");
			do {
				printf("%s%.2x", (i == ifi->ifi_hlen) ? "" : ":", *ptr++);
			}while(--i > 0);
			printf("\n");
		}
		//MTU
		if (ifi->ifi_mtu != 0)
			printf("\tMTU: %d\n", ifi->ifi_mtu);
		//IP
		if ((sa = ifi->ifi_addr) != NULL) 
			printf("\tIP addr: %s\n", (char *)inet_ntoa(((struct sockaddr_in *)sa)->sin_addr));
		//BCAST
		if ((sa = ifi->ifi_brdaddr) != NULL) 
			printf("\tbroadcast addr: %s\n", (char *)inet_ntoa(((struct sockaddr_in *)sa)->sin_addr));
		//P2P
		if ((sa = ifi->ifi_dstaddr) != NULL) 
			printf("\tdestination addr: %s\n", (char *)inet_ntoa(((struct sockaddr_in *)sa)->sin_addr));

	}

	free_ifi_info(ifihead);
	return EXIT_SUCCESS;
}

